<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Account/classes/PhpFox_ComponentMemberships.class.php, $Author:  $ */

/**
 * Component for edit/create memberships
 *
 * @package module.account
 * @version $Id: PhpFox_ComponentMemberships.class.php 170 2008-01-18 21:11:52Z phpfoxsv $
 *
 */
class PhpFox_Mod_Account_ComponentMemberships extends BaseComponent
{
	/** Processing
	 */
	function process()
	{
	    $oSrvSec = $this->_oModule->getService('Security');
	    /* @var $oSrvSec PhpFox_Mod_Account_ServiceSecurity */

		$oReq = &App::getRequest();

		App::loadClass('file/Image');
		$oImage = &new file_Image();

		$aValFields = array();

		$sDestPath = App::getParam('membership.pic.path');

		$sCreate = $oReq->get('create');
		$iMemberType = $oReq->get('type');

		if ( !$iMemberType && $iMemberType != '0' && $sCreate != 'new' )
		{
			trigger_error("no membershp id for: ". $iMemberType ."", E_USER_ERROR);
		}

		if ( !$sCreate )
		{
			$aCond = array('membership_id' => ' = "'. $iMemberType .'"');
	    	list($aMemberships, $aValFields) = $oSrvSec->getMembershipsList($aCond);

	    	if ( $iMemberType == '2' )
	    	{
	    		$aValFields = array();
	    	}
	    }
	    else
	    {
	    	list($aMemberships, $aValFields) = $oSrvSec->setupNewMembership();
	    }

		if ( $iMemberType != '2' )
		{
	    	//create validator
        	$aValFields = array(
	    	    'aMemb[max_upload]' => array('title' => App::format('max_upload_space_in_bytes'), 'def' => 'integer'),
	    	    'aMemb[max_inbox]'  => array('title' => App::format('inbox_limit'), 'def' => 'integer'),
        	);
		}

		$aNewMemb = array(
		    'price'      => 0.00,
		    'max_upload' => 0,
			'max_inbox'  => 0,
		);

        $oValidator = App::newObject('Validator', $aValFields); //update validator
        /* @var $oValidator Validator */

        $aValFields['aMemb[title]'] = array('title' => App::format('membership_title'), 'def' => 'required');

        $oValidatorNew = App::newObject('Validator', $aValFields); //creat validator
        /* @var $oValidatorNew Validator */

		$oTpl = &$this->_oModule->getTemplate();

	    switch ($oReq->getAction())
		{
	        case 'create_membership':
		        $aMemb = $oReq->getArray('aMemb');
	            if ($oValidatorNew->isValid($oReq->getAll()))
	            {
	            	$aMemb['img'] = $_FILES['image']['name'];
    	            if ($oSrvSec->createMembership($aMemb, $oReq->getArray('aPerm')))
                    {
                    	if ( isset($_FILES['image']['name']) )
                    	{
        					$sFileExt = $oImage->getFileType($_FILES['image']['name']);
        					$oImage->upload('image', $sDestPath, str_replace("." .$sFileExt, "", $_FILES['image']['name']), $sFileExt);
                    	}

                        $sMess = App::format('Mod_Account.membership.created', array($aMemb['title']));
                        App::gotoUrl(App::getPageName(), array('create' => 'new'), $sMess, 'message', 'Memberships');
                    }
	            }
	            else
	            {
	            	  //postback
                    $aNewMemb = $aMemb;
                    $this->addErrors($oValidatorNew->getErrors());
	            }
                $oTpl->assignSrc(array(
					'aErrorsNew' => $this->getErrors(),
				));
    	        break;

	        case 'update_membership':
	            $aMemb = $oReq->getArray('aMemb');
	            $bIsStaff = in_array($aMemb['membership_id'],
                                     array(App::getParam('Mod_Account.membership.admin'),
                                           App::getParam('Mod_Account.membership.staff')) );

	            if ($bIsStaff || $oValidator->isValid($oReq->getAll()) )
	            {
    	            if ($oSrvSec->updateMembership($aMemb, $oReq->getArray('aPerm')))
    	            {
    	             	$oCache = &App::newObject("Cache");
    	             	$oCache->rmFile("memb2perm". $aMemb['membership_id'] .".php");
    	             	$oCache->rmFile("membership". $aMemb['membership_id'] .".php");
                        $sMess = App::format('Mod_Account.membership.updated', array($aMemb['title']));
                        App::gotoUrl(App::getPageName(), array('type' => $iMemberType), $sMess, 'message', 'Memberships');
    	            }
	            }
	            else
	            {
	                //postback
                    $this->addErrors($oValidator->getErrors());
	            }
                $oTpl->assignSrc(array(
					'aErrors'.$aMemb['membership_id'] => $oValidator->getErrors(),
				));
    	        break;

	        case 'delete_membership':
	            $aMemb = $oReq->getArray('aMemb');
	            if ($oSrvSec->deleteMembership($aMemb['membership_id']))
	            {
	                $oUrl = &App::getUrl();
	                $sMess = App::format('Mod_Account.membership.deleted', array($aMemb['title']));
	                App::forward($oUrl->getUrl(), $sMess, 'message', App::getPageName(), 'Memberships');
	            }
	            else
	            {
	                $this->addErrors($oSrvSec->getErrors());
	            }
	            break;
	    }

	    //get list of membership images
        $aMemImages = array();
        $d = opendir(App::getParam('membership.pic.path'));
        while($sFile = readdir($d))
        {
            if ( substr($sFile, -4) == '.gif' || substr($sFile, -4) == '.jpg' || substr($sFile, -4) == '.png' )
            {
                $aMemImages[$sFile] = $sFile;
            }
        }

		$oTpl->assign(array
		(
			'isWritable' => $oImage->isWritable($sDestPath),
			'sDestPath' => App::format('Mod_Account.ensure_writable', str_replace(App::getParam('path'), "", $sDestPath)),
			'sCreate' => $sCreate,
			'aMemberships' => $aMemberships,
			'aMemImages'   => $aMemImages,
			'aNewMemb'     => $aNewMemb,
			'bIsSubscr'    => App::getSetting('sub_system'),
			'aErrors'      => $this->getErrors(),
		));

		$srcHtml = $oTpl->fetch('Memberships.html');
		return $srcHtml;
	}

}
?>